<template>
  <div class="warehouse-change-list-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>仓库变动 申请列表</h2>
      <el-button type="text" @click="handleBack">返回</el-button>
    </div>

    <!-- 查询表单区域 -->
    <el-form 
      :model="searchForm" 
      ref="searchFormRef" 
      label-width="80px"
      class="search-form"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="开始时间">
            <el-date-picker 
              v-model="searchForm.startTime" 
              type="date" 
              placeholder="选择开始时间" 
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束时间">
            <el-date-picker 
              v-model="searchForm.endTime" 
              type="date" 
              placeholder="选择结束时间" 
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="文员">
            <el-input v-model="searchForm.clerk" placeholder="输入文员" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="财务">
            <el-input v-model="searchForm.finance" placeholder="输入财务" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="仓库">
            <el-select v-model="searchForm.warehouse" placeholder="选择仓库" clearable>
              <el-option 
                v-for="item in warehouseOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="品牌">
            <el-select v-model="searchForm.brand" placeholder="选择品牌" clearable>
              <el-option 
                v-for="item in brandOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" @click="handleSearch">筛选</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 申请列表表格 -->
    <el-table 
      :data="filteredApplications" 
      border 
      stripe 
      class="application-table"
      v-loading="loading"
    >
      <el-table-column prop="index" label="序号" width="80" align="center" />
      <el-table-column prop="docType" label="单据类型"  align="center" />
      <el-table-column prop="recordTime" label="录单时间"  align="center" />
      <el-table-column prop="docNo" label="单据编号" align="center" width="150" />
      <el-table-column prop="warehouse" label="仓库" align="center" />
      <el-table-column prop="brand" label="品牌" align="center" />
      <el-table-column prop="clerk" label="文员提交人" align="center" />
      <el-table-column prop="financeAudit" label="财务审核人" align="center" />
      <el-table-column prop="warehouseConfirm" label="仓库员确认"  align="center"/>
      <el-table-column prop="otherRemark" label="其他备注" align="center" />
      <el-table-column label="操作" fixed="right" width="250" >
        <template #default="scope">
          <el-button 
            type="primary" 
            
            @click="handleViewDetail(scope.row)"
          >
            查看
          </el-button>
          <el-button 
            type="warning" 
     
            @click="handleReject(scope.row)"
          >
            驳回
          </el-button>
          <el-button 
            type="danger" 
           
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination">
      <span class="total-info">共 {{ totalRecords }} 条 共 {{ totalPages }} 页</span>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="totalRecords"
        layout="prev, pager, next, jumper, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog 
      v-model="detailVisible" 
      title="申请详情" 
      width="800px"
    >
      <el-descriptions column="2" border>
        <el-descriptions-item label="单据类型">{{ currentApplication.docType }}</el-descriptions-item>
        <el-descriptions-item label="录单时间">{{ currentApplication.recordTime }}</el-descriptions-item>
        <el-descriptions-item label="单据编号">{{ currentApplication.docNo }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{ currentApplication.warehouse }}</el-descriptions-item>
        <el-descriptions-item label="品牌">{{ currentApplication.brand }}</el-descriptions-item>
        <el-descriptions-item label="文员提交人">{{ currentApplication.clerk }}</el-descriptions-item>
        <el-descriptions-item label="财务审核人">
          <el-tag 
            :type="currentApplication.financeAudit === '未确认' ? 'info' : 'success'"
          >
            {{ currentApplication.financeAudit }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="仓库员确认">
          <el-tag 
            :type="currentApplication.warehouseConfirm === '未确认' ? 'info' : 'success'"
          >
            {{ currentApplication.warehouseConfirm }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="其他备注">{{ currentApplication.otherRemark || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="detail-table-container" v-if="currentApplication.details">
        <h3 class="detail-table-title">变动明细</h3>
        <el-table 
          :data="currentApplication.details" 
          border 
          stripe 
          class="detail-table"
        >
          <el-table-column prop="productName" label="产品名称" />
          <el-table-column prop="productNo" label="产品编号" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="reason" label="变动原因" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 驳回确认弹窗 -->
    <el-dialog 
      v-model="rejectConfirmVisible" 
      title="确认驳回" 
      width="300px"
    >
      <p>确定要驳回此申请吗？</p>
      <el-form-item label="驳回原因">
        <el-input 
          v-model="rejectReason" 
          type="textarea" 
          rows="3" 
          placeholder="请输入驳回原因"
        />
      </el-form-item>
      <template #footer>
        <el-button @click="rejectConfirmVisible = false">取消</el-button>
        <el-button 
          type="warning" 
          @click="confirmReject"
        >
          确认驳回
        </el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog 
      v-model="deleteConfirmVisible" 
      title="确认删除" 
      width="300px"
    >
      <p>确定要删除此申请吗？此操作不可撤销。</p>
      <template #footer>
        <el-button @click="deleteConfirmVisible = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="confirmDelete"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 路由实例
const router = useRouter()

// 状态管理
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalRecords = ref(0)
const totalPages = ref(0)
const detailVisible = ref(false)
const rejectConfirmVisible = ref(false)
const deleteConfirmVisible = ref(false)
const currentApplication = ref({})
const deleteApplicationId = ref(null)
const rejectReason = ref('')

// 查询表单数据
const searchForm = reactive({
  startTime: '',
  endTime: '',
  clerk: '',
  finance: '',
  warehouse: '',
  brand: ''
})

// 仓库下拉选项
const warehouseOptions = [
  { label: '仓库1', value: '仓库1' },
  { label: '仓库2', value: '仓库2' },
  { label: '仓库3', value: '仓库3' }
]

// 品牌下拉选项
const brandOptions = [
  { label: 'gucci', value: 'gucci' },
  { label: 'lv', value: 'lv' },
  { label: 'chanel', value: 'chanel' }
]

// 申请列表数据
const applicationList = reactive([
  {
    id: 1,
    index: 1,
    docType: '销售单',
    recordTime: '2022.8.30',
    docNo: '231298213617824',
    warehouse: '仓库1',
    brand: 'gucci',
    clerk: '陈辉',
    financeAudit: '李悦',
    warehouseConfirm: '未确认',
    otherRemark: '',
    details: [
      { productName: 'gucci手袋', productNo: 'GC001', quantity: 2, reason: '客户购买' },
      { productName: 'gucci腰带', productNo: 'GC002', quantity: 1, reason: '客户购买' }
    ]
  },
  {
    id: 2,
    index: 2,
    docType: '报损单',
    recordTime: '2022.8.30',
    docNo: '231298213617824',
    warehouse: '仓库1',
    brand: 'gucci',
    clerk: '陈辉',
    financeAudit: '未确认',
    warehouseConfirm: '未确认',
    otherRemark: '',
    details: [
      { productName: 'gucci口红', productNo: 'GC003', quantity: 1, reason: '产品损坏' }
    ]
  },
  {
    id: 3,
    index: 3,
    docType: '报溢单',
    recordTime: '2022.8.30',
    docNo: '231298213617824',
    warehouse: '仓库2',
    brand: 'gucci',
    clerk: '陈辉',
    financeAudit: '未确认',
    warehouseConfirm: '未确认',
    otherRemark: '',
    details: [
      { productName: 'gucci香水', productNo: 'GC004', quantity: 1, reason: '盘点溢余' }
    ]
  },
  {
    id: 4,
    index: 4,
    docType: '退货单',
    recordTime: '2022.8.30',
    docNo: '231298213617824',
    warehouse: '仓库2',
    brand: 'gucci',
    clerk: '陈辉',
    financeAudit: '未确认',
    warehouseConfirm: '未确认',
    otherRemark: '',
    details: [
      { productName: 'gucci墨镜', productNo: 'GC005', quantity: 1, reason: '客户退货' }
    ]
  },
  {
    id: 5,
    index: 5,
    docType: '换货单',
    recordTime: '2022.8.30',
    docNo: '231298213617824',
    warehouse: '仓库2',
    brand: 'gucci',
    clerk: '陈辉',
    financeAudit: '未确认',
    warehouseConfirm: '未确认',
    otherRemark: '',
    details: [
      { productName: 'gucci钱包', productNo: 'GC006', quantity: 1, reason: '客户换货' }
    ]
  }
])

// 过滤后的申请列表（分页+搜索）
const filteredApplications = computed(() => {
  // 搜索过滤
  let result = applicationList.filter(item => {
    const matchStartTime = !searchForm.startTime || item.recordTime >= searchForm.startTime.replace(/-/g, '.')
    const matchEndTime = !searchForm.endTime || item.recordTime <= searchForm.endTime.replace(/-/g, '.')
    const matchClerk = !searchForm.clerk || item.clerk.includes(searchForm.clerk)
    const matchFinance = !searchForm.finance || item.financeAudit.includes(searchForm.finance)
    const matchWarehouse = !searchForm.warehouse || item.warehouse === searchForm.warehouse
    const matchBrand = !searchForm.brand || item.brand === searchForm.brand
    return matchStartTime && matchEndTime && matchClerk && matchFinance && matchWarehouse && matchBrand
  })

  // 更新总数
  totalRecords.value = result.length
  totalPages.value = Math.ceil(totalRecords.value / pageSize.value)

  // 分页处理
  const startIndex = (currentPage.value - 1) * pageSize.value
  return result.slice(startIndex, startIndex + pageSize.value)
})

// 生命周期：初始化
onMounted(() => {
  // 模拟加载数据
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
})

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 搜索事件
const handleSearch = () => {
  currentPage.value = 1 // 搜索后重置到第一页
}

// 返回事件
const handleBack = () => {
  router.back()
}

// 查看详情
const handleViewDetail = (row) => {
  currentApplication.value = { ...row }
  detailVisible.value = true
}

// 驳回申请（显示确认）
const handleReject = (row) => {
  currentApplication.value = { ...row }
  rejectConfirmVisible.value = true
}

// 确认驳回
const confirmReject = () => {
  if (!rejectReason.value) {
    ElMessage.warning('请输入驳回原因')
    return
  }
  loading.value = true
  setTimeout(() => {
    // 模拟驳回逻辑
    const index = applicationList.findIndex(item => item.id === currentApplication.value.id)
    if (index !== -1) {
      applicationList[index].financeAudit = '已驳回'
      applicationList[index].warehouseConfirm = '已驳回'
    }
    rejectConfirmVisible.value = false
    rejectReason.value = ''
    loading.value = false
    ElMessage.success('申请已驳回')
  }, 500)
}

// 删除申请（显示确认）
const handleDelete = (id) => {
  deleteApplicationId.value = id
  deleteConfirmVisible.value = true
}

// 确认删除
const confirmDelete = () => {
  loading.value = true
  setTimeout(() => {
    const index = applicationList.findIndex(item => item.id === deleteApplicationId.value)
    if (index !== -1) {
      applicationList.splice(index, 1)
    }
    deleteConfirmVisible.value = false
    loading.value = false
    ElMessage.success('申请已删除')
  }, 500)
}
</script>

<style scoped>
.warehouse-change-list-page {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
  }

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.search-form {
  margin-bottom: 20px;
}

.application-table {
  width: 100%;
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.total-info {
  color: #606266;
  font-size: 14px;
}

.detail-table-container {
  margin-top: 20px;
}

.detail-table-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}

.detail-table {
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-form .el-row {
    flex-wrap: wrap;
  }
}
</style>